import React from 'react'

export default function ImageCard({ item, onView, onDelete }){
  const tags = item.tags || (item.detections ? item.detections.map(d => (d.class || d.label || d.name)).filter(Boolean) : [])
  const score = item.score ?? (item.detections && Array.isArray(item.detections) && item.detections[0] ? (item.detections[0].confidence ?? item.detections[0].score) : '')

  return (
    <div className="img-card fade-in" role="article" aria-label={item.name || 'image-card'}>
      <img src={item.dataUrl || item.url || item.src} alt={item.name} />
      {/* top-left score badge (if available) */}
      {score !== '' && score != null && (
        <div style={{position:'absolute', left:10, top:10}}>
          <div className="badge" style={{background:'#0b934d', padding:'6px 8px', fontSize:12}}>
            {(typeof score === 'number' ? (score >= 0 && score <= 1 ? (score*100).toFixed(0) + '%' : Number(score).toFixed(2)) : String(score))}
          </div>
        </div>
      )}

      <div className="meta">
        <div className="badge secondary" title={item.name || ''}>
          {item.name ? (item.name.length > 18 ? item.name.slice(0, 16) + '…' : item.name) : '未命名'}
        </div>
        {tags.slice(0,2).map((t, i) => (
          <div key={i} className="badge" style={{background:'#0b4bd6', opacity:0.95}}>{t}</div>
        ))}
      </div>

      <div className="card-actions">
        <button className="icon-btn" title="查看详情" onClick={() => onView && onView(item)}>
          <svg width="16" height="16" viewBox="0 0 24 24"><path fill="#111" d="M12 5C7 5 2.73 8.11 1 12c1.73 3.89 6 7 11 7s9.27-3.11 11-7c-1.73-3.89-6-7-11-7zm0 12a5 5 0 110-10 5 5 0 010 10z"/></svg>
        </button>

        <button
          className="icon-btn"
          title="删除"
          onClick={() => {
            if (!onDelete) return
            // 确认删除（组件层做一次确认，具体项目可由上层处理）
            if (window.confirm(`确认删除 "${item.name || '此图片'}"？此操作不可恢复（仅演示）`)) {
              onDelete(item.id ?? item)
            }
          }}
          style={{marginLeft:8}}
        >
          <svg width="14" height="14" viewBox="0 0 24 24"><path fill="#b21" d="M9 3v1H4v2h16V4h-5V3H9zm-1 6v9h2v-9H8zm5 0v9h2v-9h-2z"/></svg>
        </button>
      </div>
    </div>
  )
}